package com.example.blockchain.utils;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DataUtils {
    public static boolean isNotice = false;

    /**
     * 把字符串写入文件
     * @param relativePath
     * @param data
     */
    public static boolean writeFile(String relativePath, String data) {
        try {
            File file = new File(relativePath);
            FileUtils.writeStringToFile(file, data);
        } catch (IOException e) {

            //e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String readFile(String relativePath) {
        String result = "";
        try {

            File file = new File(relativePath);
            result = FileUtils.readFileToString(file);
        } catch (IOException e) {
        }
        return result;
    }
    public static boolean findFile(String relativePath) {

        File file = new File(relativePath);
        if(file.exists()) {
            return true;
        }else {
            try {
                file.mkdirs();
                String path=getRelativePath("/db/block/blockchain.db");
                File file2 = new File(path);
                file2.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }
    public static String getRelativePath(String relativePath) {
        return System.getProperty("user.dir") + relativePath;
    }
    /**
     * dir: "block" + blockIndex
     * table: "block" + blockIndex
     * @param blockIndex
     * @return
     */
    public static String getBlockSerial(String blockIndex) {
        String index = "";
        if(blockIndex.length() < 5) {
            index = "0";
        }else {
            index = blockIndex.substring(0, blockIndex.length() - 4);
        }
        return index;
    }

    public static String getBlockPath(String blockIndex, Date currentTime) {
        String path = "/ws/block" + DataUtils.getBlockSerial(blockIndex);
        String blockName = "no" + blockIndex + "-" + currentTime.getTime() + ".bnk";
        return path + "/" + blockName;
    }
    public static String getTempBlockPath(String blockIndex) {
        String path = "/ws/blockTemp";
        String blockName = "no" + blockIndex + ".bnk";
        return path + "/" + blockName;
    }

    public static String getBlockString(String blockPath) {
        return readFile(blockPath);
    }

}
